<script setup>
import { ref } from "vue";
import { NewWs } from "../utils/ws";
const userId = ref("");
const roomId = ref("");
let localVideo = ref(null);
let remoteVideo = ref(null);
defineProps({
  msg: String,
});
let ws;
let mediaStreamTrack = null;
let remoteMediaStreamTrack = null;
let peer = null;
const startWs = () => {
  ws = NewWs(
    `ws://localhost:8999/ws/` + userId.value,
    (e) => {
      console.log("open:", e);

      // 发送房间号
      ws.send(roomId.value);

      peer = new RTCPeerConnection();

      // 当所有媒体协商，网络协商（ice） 结束后会调用此方法
      peer.ontrack = (event) => {
        console.log("显示远程屏幕：", event);
        remoteMediaStreamTrack = event.streams[0];
        remoteVideo.value.srcObject = remoteMediaStreamTrack;
        remoteVideo.value.play();
      };

      peer.onicecandidate = (event) => {
        console.log("onicecandidate: ", event);
        if (event.candidate) {
          console.log("icecandidate: ", event.candidate);
          // 发送自身的网络信息到通信方
          ws.send(
            JSON.stringify({
              type: "candidate",
              sdpMLineIndex: event.candidate.sdpMLineIndex,
              sdpMid: event.candidate.sdpMid,
              candidate: event.candidate.candidate,
              sessionId: roomId.value,
            })
          );
        }
      };
      navigator.mediaDevices
        .getUserMedia({ audio: true, video: true })
        // 参数表示需要同时获取到音频和视频
        .then((stream) => {
          // 获取到优化后的媒体流
          localVideo.value.srcObject = stream;
          //这里保存下来stream对象只是为了后续关闭摄像头的时候使用
          mediaStreamTrack = stream;

          // 将音视频添加到 peer 中
          stream.getTracks().forEach((track) => peer.addTrack(track, stream));

          localVideo.value.play();
          console.log(localVideo);
        })
        .catch((err) => {
          // 捕获错误
          console.log(err);
          console.log(localVideo.value);
        });
    },
    (e) => {
      console.log("error:", e);
    },
    (e) => {
      console.log("close:", e);
    },
    (e) => {
      console.log(e);
      console.log("e.data: ", e.data);
      // 记得反序列化 ，否则返回数据是个字符串
      const data = JSON.parse(e.data);
      console.log(".data: ", data);
      if (data.type != null) {
        switch (data.type) {
          case "offer":
            peer.setRemoteDescription({
              type: "offer",
              sdp: data.data,
            });

            // 接收端创建answer并发送给发起端
            peer.createAnswer().then(async (answer) => {
              await peer.setLocalDescription(answer);
              ws.send(
                JSON.stringify({
                  type: "answer",
                  data: answer.sdp,
                  sessionId: roomId.value, // 为了方便，这里写死
                })
              );
            });
            break;
          case "answer":
            peer.setRemoteDescription({
              type: "answer",
              sdp: data.data,
            });
            break;
          case "candidate":
            console.log("candidate-----------", data);
            peer.addIceCandidate(
              new RTCIceCandidate({
                sdpMLineIndex: data.sdpMLineIndex,
                sdpMid: data.sdpMid,
                candidate: data.candidate,
              })
            );
            break;
        }
      }
      console.log("message:", e);
    }
  );
  console.log(userId.value);
};

const callRtc = () => {
  peer.createOffer().then(async (offer) => {
    await peer.setLocalDescription(offer);
    console.log(offer);
    console.log(offer.sdp);
    ws.send(
      JSON.stringify({
        type: "offer",
        data: offer.sdp,
        sessionId: roomId.value, // 为了方便，这里写死
      })
    );
  });
};

const closeWs = () => {
  if (ws !== null) {
    ws.close();
  }
  if (localVideo !== null || localVideo.value !== null) {
    localVideo.value.srcObject = null;
  }
  if (mediaStreamTrack != null) {
    mediaStreamTrack.getVideoTracks().forEach((track) => {
      track.stop();
    });
  }
  if (remoteVideo !== null || remoteVideo.value !== null) {
    remoteVideo.value.srcObject = null;
  }
  if (remoteMediaStreamTrack != null) {
    remoteMediaStreamTrack.getVideoTracks().forEach((track) => {
      track.stop();
    });
  }
};

const count = ref(0);

const list = ref([{
  "name": "zhangSan",
  "age": 14,
  "sex": "男"
}, {
  "name": "zhangSan111",
  "age": 1411,
  "sex": "男11"
}])
</script>

<template>
  <div>
    <video ref="localVideo"></video>
    <video ref="remoteVideo"></video>

    <button v-on:click="startWs">开启ws</button>
    <button v-on:click="closeWs">关闭ws</button>
    <p></p>
    userId:<input type="text" v-model="userId" /> <br /><br />
    roomId:<input type="text" v-model="roomId" />
    <p>userId: {{ userId }}</p>
    <p>roomId: {{ roomId }}</p>
    <button v-on:click="callRtc">Call</button>

    <div>
      <div class="a" v-for="(item, index) in list" :key="index">
        <div class="b" v-for="(itemValue, itemKey) in item" :key="itemKey">
          {{ itemValue }}
        </div>
      </div>
    </div>

  </div>
</template>

<style scoped>
.read-the-docs {
  color: #888;
}

.a {
  display: flex;
}
</style>
